import os
from PySide6.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QPushButton, QTableWidget, 
    QTableWidgetItem, QHeaderView, QFileDialog, QMessageBox, QLineEdit
)
from PySide6.QtCore import Qt
from src.ui.i18n import _
from src.utils.srt_parser import SRTParser, Subtitle

class SubtitleEditorDialog(QDialog):
    def __init__(self, srt_path, parent=None):
        super().__init__(parent)
        self.srt_path = srt_path
        self.subtitles = []

        self.setWindowTitle(_("Subtitle Editor"))
        self.setMinimumSize(800, 600)

        self._setup_ui()
        self._connect_signals()
        self._load_srt()

    def _setup_ui(self):
        main_layout = QVBoxLayout(self)

        # Top: Maybe a video/audio player in the future
        # For now, just a placeholder
        player_placeholder = QLineEdit(_("Video/Audio Player Placeholder"))
        player_placeholder.setReadOnly(True)
        main_layout.addWidget(player_placeholder)

        # Middle: Subtitle Table
        self.table = QTableWidget()
        self.table.setColumnCount(4)
        self.table.setHorizontalHeaderLabels([_("ID"), _("Start Time"), _("End Time"), _("Text")])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch)
        self.table.setColumnWidth(0, 50)
        self.table.setColumnWidth(1, 120)
        self.table.setColumnWidth(2, 120)
        main_layout.addWidget(self.table)

        # Bottom: Buttons
        button_layout = QHBoxLayout()
        self.save_button = QPushButton(_("Save"))
        self.save_as_button = QPushButton(_("Save As..."))
        self.close_button = QPushButton(_("Close"))
        
        button_layout.addStretch()
        button_layout.addWidget(self.save_button)
        button_layout.addWidget(self.save_as_button)
        button_layout.addWidget(self.close_button)
        main_layout.addLayout(button_layout)

    def _connect_signals(self):
        self.save_button.clicked.connect(lambda: self.save_srt(self.srt_path))
        self.save_as_button.clicked.connect(self.save_srt_as)
        self.close_button.clicked.connect(self.close)

    def _load_srt(self):
        try:
            parser = SRTParser(self.srt_path)
            parser.parse()
            self.subtitles = parser.subtitles
            self.populate_table()
        except Exception as e:
            QMessageBox.critical(self, _("Error"), _("Failed to load SRT file: {}").format(e))
            self.close()

    def populate_table(self):
        self.table.setRowCount(len(self.subtitles))
        for i, sub in enumerate(self.subtitles):
            self.table.setItem(i, 0, QTableWidgetItem(str(sub.index)))
            self.table.setItem(i, 1, QTableWidgetItem(sub.start))
            self.table.setItem(i, 2, QTableWidgetItem(sub.end))
            self.table.setItem(i, 3, QTableWidgetItem(sub.text))
        self.table.resizeRowsToContents()

    def save_srt(self, path):
        self._update_subtitles_from_table()
        # Create a parser instance just for writing
        parser = SRTParser(path)
        parser.subtitles = self.subtitles # Use the current (potentially modified) subtitles
        
        # The write method in the original parser needs the translated texts,
        # so we'll just extract the text from our current subtitles.
        texts_to_write = [sub.text for sub in self.subtitles]
        
        try:
            parser.write(path, texts_to_write)
            QMessageBox.information(self, _("Success"), _("File saved successfully to {}").format(path))
            return True
        except Exception as e:
            QMessageBox.critical(self, _("Error"), _("Failed to save SRT file: {}").format(e))
            return False

    def save_srt_as(self):
        new_path, _ = QFileDialog.getSaveFileName(self, _("Save SRT As..."), self.srt_path, "SRT Files (*.srt)")
        if new_path:
            if self.save_srt(new_path):
                self.srt_path = new_path # Update path only on successful save

    def _update_subtitles_from_table(self):
        updated_subtitles = []
        for i in range(self.table.rowCount()):
            original_sub = self.subtitles[i]
            text = self.table.item(i, 3).text()
            
            # Create a new Subtitle object with the updated text
            updated_sub = original_sub._replace(text=text)
            updated_subtitles.append(updated_sub)
        self.subtitles = updated_subtitles
